package com.shaozi.nc.configuration;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

@Configuration
@Order(2)
@EnableMongoRepositories(basePackages = "com.shaozi", mongoTemplateRef = "shaoziTemplate")
public class NCMongoConfiguration extends AbstractMongoConfiguration {

	@Value("${nc.db.mongo.dbname}")
	private String dbName;
	@Value("${nc.db.mongo.ip}")
	private String host;
	@Value("${nc.db.mongo.port}")
	private int port;
	@Value("${nc.db.mongo.username}")
	private String userName;
	@Value("${nc.db.mongo.passwd}")
	private String password;

	@Autowired
	private ApplicationContext appContext;

	@Override
	protected String getDatabaseName() {
		return dbName;
	}

	@Override
	public Mongo mongo() throws Exception {
		List<MongoCredential> credentials = new ArrayList<>();
		MongoCredential credential = MongoCredential.createCredential(userName, dbName, password.toCharArray());
		credentials.add(credential);

		ServerAddress servAddr = new ServerAddress(host, port);
		MongoClient client = new MongoClient(servAddr, credentials);
		return client;
	}

	@Bean(name = "shaoziTemplate")
	@Override
	public MongoTemplate mongoTemplate() throws Exception {
		// return super.mongoTemplate();
		MongoDbFactory factory = mongoDbFactory();

		MongoMappingContext mongoMappingContext = new MongoMappingContext();
		mongoMappingContext.setApplicationContext(appContext);

		MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(factory),
				mongoMappingContext);
		// 移除_class
		converter.setTypeMapper(new DefaultMongoTypeMapper(null));

		return new MongoTemplate(factory, converter);
	}

	@Bean(name = "shaoziMongoDbFactory")
	@Override
	public MongoDbFactory mongoDbFactory() throws Exception {
		return super.mongoDbFactory();
	}

}
